from fastapi import APIRouter, Request, Form, Response
from starlette.responses import RedirectResponse
from starlette.templating import Jinja2Templates
from models import *
import uuid

user_app = APIRouter()
templates = Jinja2Templates(directory="templates")


@user_app.get('/login')
async def login(request: Request):
    return templates.TemplateResponse('login.html', {'request': request})


@user_app.post('/login-endpoint')
async def login_post(request: Request, username: str = Form(), password: str = Form()):
    user = await User.get_or_none(username=username)
    if user is None:
        return templates.TemplateResponse('login.html', {'request': request, 'error': '用户不存在'})
    elif password != user.password:
        return templates.TemplateResponse('login.html', {'request': request, 'error': '密码错误'})
    else:
        response = RedirectResponse('/douyin/task', status_code=303)
        response.set_cookie(key='uid', value=user.uid, max_age=10000000000000000)
        return response


@user_app.post('/register-endpoint')
async def register(request: Request, username: str = Form(), password: str = Form()):
    result = await User.get_or_none(username=username)
    if result is not None:
        return templates.TemplateResponse('login.html', {'request': request, 'error': '用户名已存在'})
    else:
        uid = str(uuid.uuid4())
        await User.create(uid=uid, username=username, password=password)
        response = RedirectResponse('/douyin/task', status_code=303)
        response.set_cookie(key='uid', value=uid)
        return response


@user_app.get('/logout')
async def logout():
    response = RedirectResponse('/account/login')
    response.delete_cookie(key='uid')
    return response
